package org.firebug.spring.boot.ssj.tools;

import org.springframework.beans.BeanUtils;

import java.util.*;

public final class BeanTools {
    private BeanTools() {}

    public static <S, T> T convertBean(S sourceBean, Class<T> targetClass) {
        return convertBean(sourceBean, targetClass, null);
    }

    public static <S, T> T convertBean(S sourceBean, Class<T> targetClass, T targetDefault) {
        if (sourceBean == null) {
            return targetDefault;
        }
        try {
            T target = targetClass.newInstance();
            BeanUtils.copyProperties(sourceBean, target);
            return target;
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }
        return targetDefault;
    }

    public static <S, T> List<T> convertList(Collection<S> sourceBeans, Class<T> targetClass) {
        List<T> list = new ArrayList<>(sourceBeans.size());
        for (S sourceBean : sourceBeans) {
            list.add(convertBean(sourceBean, targetClass));
        }
        return list;
    }

    public static <S, T> Set<T> convertSet(Collection<S> sourceBeans, Class<T> targetClass) {
        Set<T> set = new HashSet<>();
        for (S sourceBean : sourceBeans) {
            set.add(convertBean(sourceBean, targetClass));
        }
        return set;
    }

    public static <S, T> Collection<T> convertCollection(Collection<S> sourceBeans, Collection<T> targetBeans, Class<T> targetClass) {
        for (S sourceBean : sourceBeans) {
            targetBeans.add(convertBean(sourceBean, targetClass));
        }
        return targetBeans;
    }
}
